
let _Vue = null;

export default class VueRouter {
    static install(Vue) {
        // 1. 判断当前插件是否被安装
        if (VueRouter.install.installed) {
            return;
        }
        VueRouter.install.installed = true;
       
        // 2.把传入的Vue 构造函数绑定到全局对象
        _Vue = Vue

        // 3.把创建Vue实例时候传入的router 注入到Vue实例上
        _Vue.mixin({
            beforeCreate () {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                }
            }
        })
    }

    constructor (option) {
        this.option = option
        this.routeMap = {}
        this.data = _Vue.observable({
            current: '/'
        })
        this.init()
        this.initEvent()
    }

    init () {
        this.createRouteMap()
        this.initComponents(_Vue)
    }
    createRouteMap () {
        // 遍历所有的路由规则，把路由规则拆分成键值对的形式保存在routerMap当中
        this.option.routes.forEach(route => {
            this.routeMap[route.path] = route.component
        })
    }

    initComponents (Vue) {
        let self = this
        Vue.component('router-link', {
            name: 'router-link',
            props: {
                to: String
            },
            render(h) {
                return h('a', {
                    attrs: {
                        href: '#' + this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                }, [this.$slots.default])
            },
            methods: {
                clickHandler(e) {
                    e.preventDefault()
                    window.location.hash = '#' + this.to
                    this.$router.data.current = this.to
                }
            }
            // template: '<a :href="to"><solt></solt></a>'
        })

        Vue.component('router-view', {
            render(h) {
                const compoent = self.routeMap[self.data.current]
                return h(compoent)
            }
        })
    }

    initEvent() {
        window.addEventListener('load', () => {
            if (!window.location.hash) {
                window.location.hash = '#/'
            }
        })

        window.addEventListener('hashchange', () => {
            if (!window.location.hash) {
                window.location.hash = '#/'
            }
            this.data.current = window.location.hash.substr(1)
        })
    }
}
